/*
 * utils.c
 *
 *  Created on: May 6, 2013
 *      Author: moises
 */

#include <sys/time.h>
#include <stdio.h>
#include <stdlib.h>
#include "utils.h"

struct timeval start, stop;
unsigned diffsec, diffusec;

void time_log_start() {
	gettimeofday(&start, NULL);
}

void time_log_stop() {
	gettimeofday(&stop, NULL);
	compute_time_and_flush();
}

/* does the same as "time_log_stop()"
 * but updates the start time.
 * It's useful when you want to measure
 * the time elapsed in many checkpoints
 * of your code (like at the end of a 'for' loop)
 */
void time_log_snapshot() {
	time_log_stop();
	start = stop;
}

void compute_time_and_flush() {
	diffsec = stop.tv_sec - start.tv_sec;
	if ( stop.tv_usec >= start.tv_usec ){
		diffusec = stop.tv_usec - start.tv_usec;
	}
	else{
		diffusec = 1000000 - abs(start.tv_usec - stop.tv_usec);
		diffsec--;
	}

	printf("%d.%06d", diffsec, diffusec);
}


